package openase.audiosearch.ranking;

import openase.audio.AudioInfo;
import openase.common.Pair;

public final class AudioRanking {

	private final Pair<Integer, AudioInfo[]>[] ranking;

	AudioRanking(Pair<Integer, AudioInfo[]>[] ranking) {
		this.ranking = ranking;
	}

	public int getRankedAudiosCount() {
		return ranking.length;
	}

	public int getRankedValueAt(int index) {
		checkBounds(index);

		return ranking[index].getFirst();
	}

	public AudioInfo[] getRankedAudiosAt(int index) {
		checkBounds(index);

		return ranking[index].getSecond().clone();
	}

	private void checkBounds(int index) {
		if (index < 0 || index >= getRankedAudiosCount()) {
			throw new IndexOutOfBoundsException(index + " is not a valid index for the ranked audios.");
		}
	}

	@Override
	public String toString() {
		return toString(Integer.MAX_VALUE);
	}

	public String toString(int top) {
		final StringBuilder rankStr = new StringBuilder(1024);

		int pos = 1;

		for (int ra = 0; ra < getRankedAudiosCount() && pos <= top; ra++) {
			AudioInfo[] audios = getRankedAudiosAt(ra);
			int rankValue = getRankedValueAt(ra);

			boolean first = true;

			int i = 0;
			while (pos <= top && i < audios.length) {
				if (first) {
					rankStr.append(String.format("%4d. %s [%d]%n", pos, audios[i].getInfo(), rankValue));
					first = false;
				} else {
					rankStr.append(String.format("      %s [%d]%n", audios[i].getInfo(), rankValue));
				}
				pos++;
				i++;
			}
		}

		return rankStr.toString();
	}

}
